import { RouteRecordRaw, createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

import { Local } from '@/cache'

// import { constantRoutes } from './route'
// import { news } from './news'
// import { user } from './user'

const Layout = () => import('@/views/layout/index.vue')

export const routes: RouteRecordRaw[] = [
  {
    path: "/",
    component: Layout,
    name: "Home",
    meta: { title: "home" },
    redirect: "/home",
    children: [
      {
        path: "home",
        component: () => import("@/views/home/index.vue"),
        name: "HomeIndex",
        meta: { title: "homeIndex" },
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    name: 'Login',
    meta: {
      title: 'login'
    }
  },
]

// routes.push(...constantRoutes)
// routes.push(news)
// routes.push(user)

const router = createRouter({
  history: createWebHistory('/'),
  routes: routes
})

// 全局前置守卫
router.beforeEach((to, _from, next) => {
  if (to.path === '/login') {
    // 登录或者注册才可以往下进行
    next()
    return
  }
  const token = Local.get('token')
  if (token === null || token === '') {
    ElMessage.error('登录失败, 请先登录')
    next('/login')
    return
  }
  next()
})

// 全局后置钩子
router.afterEach((to, from) => {
  console.log(to.fullPath, from.fullPath)
})

export default router
